package com.android.mall.adapter;

import java.util.List;

import com.android.mall.activity.R;
import com.android.mall.adapter.AsyncImageLoader.ImageCallback;
import com.android.mall.data.CCrazyBuy;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class CrazyGalleryAdapter extends ArrayAdapter<CCrazyBuy>{

	private Gallery gallery;
	private AsyncImageLoader asyncImageLoader;
	private List<CCrazyBuy> crazyBuyList;
	
	public CrazyGalleryAdapter(Activity activity, List<CCrazyBuy> crazyBuyList, Gallery gallery){
		super(activity, 0, crazyBuyList);
		this.gallery = gallery;
		this.crazyBuyList = crazyBuyList;
		asyncImageLoader = new AsyncImageLoader();

	}
	
    public int getCount()
    {
        return Integer.MAX_VALUE;
    }
    
	public  View getView(int position, View convertView, ViewGroup parent){
		
		Activity activity = (Activity)getContext();
		
		//Inflate the views form XML
		View rowView = convertView;
		CrazyViewCache crazyViewCache;
		if (rowView == null){
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.home_crazy_item, null);
			crazyViewCache = new CrazyViewCache(rowView);
			rowView.setTag(crazyViewCache);
		}else{
			crazyViewCache = (CrazyViewCache)rowView.getTag();
		}

		if (position < 0){
			position = position + crazyBuyList.size();
			}
		CCrazyBuy crazyBuy = getItem(position % crazyBuyList.size());
		
		//Load the image and set it on the ImageView
		String imageUrl = crazyBuy.getImageUrl();
		ImageView imageView = crazyViewCache.getImageView();
		imageView.setTag(imageUrl);
		
		Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback(){

			public void imageLoaded(Drawable imageDrawable, String imageUrl) {
				// TODO Auto-generated method stub
				ImageView imageViewByTag = (ImageView) gallery.findViewWithTag(imageUrl);
				if ((imageViewByTag != null) && (imageDrawable != null))
					imageViewByTag.setImageDrawable(imageDrawable);
			}
			
		});
		
		if (cachedImage == null){
			imageView.setImageResource(R.drawable.no_image);
		}else{
			imageView.setImageDrawable(cachedImage);
		}
		imageView.setBackgroundResource(R.drawable.android_crazy_selected);
		
		return rowView;
		

	}
	
}
